package com.hhss.qishi.utils;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

import java.io.IOException;

public class ConvertObjectUtil {
	
	public static ObjectMapper mapper = new ObjectMapper();

	static {
	    // 转换为格式化的json
	    mapper.enable(SerializationFeature.INDENT_OUTPUT);

	    // 如果json中有新增的字段并且是实体类类中不存在的，不报错
	    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
	}
	
	/**
	 * 
	 * 将json形式字符串转换为java实体类
	 * 
	 */
	public static <T> T parse(String jsonStr, Class<T> clazz) {
	    T readValue = null;
	    try {
	        readValue = mapper.readValue(jsonStr, clazz);
	    } catch (JsonParseException e) {
	        e.printStackTrace();
	    } catch (JsonMappingException e) {
	        e.printStackTrace();
	    } catch (IOException e) {
	        e.printStackTrace();
	    }
	    return readValue;
	}

	/**
	 * Object可以是POJO，也可以是Collection或数组。
	 * 如果对象为Null, 返回"null".
	 * 如果集合为空集合, 返回"[]".
	 */
	public static String toJson(Object object) {
		try {
			// 序列化是忽略null属性
			mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
			return mapper.writeValueAsString(object);
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}


}